package cn.rongdao.jrkabao.ui.main.mainfragment;


import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicDefaultHeader;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.http.request.event.CompulsoryDownLineEvent;
import com.mifengkong.frtools.ui.adapter.recyclerview.FRBaseRecyclerAdapter;
import com.mifengkong.frtools.ui.adapter.recyclerview.FRBaseRecyclerViewHolder;
import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frtools.util.FRImageLoad;
import com.mifengkong.frwidget.recyclerview.PtrRecyclerViewUIComponent;
import com.mifengkong.frwidget.refersh.OnPullToRefreshListener;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.mifengkong.greendao.bean.ActivityIndex;
import com.mifengkong.greendao.bean.FundAndActivityCenterUrlBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseViewPagerFragment;
import cn.rongdao.jrkabao.bean.information.QuotaBean;
import cn.rongdao.jrkabao.bean.main.MainBean;
import cn.rongdao.jrkabao.bean.main.ProductListBean;
import cn.rongdao.jrkabao.bean.message.LoanMessageBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.dao.ActivityCenterDao;
import cn.rongdao.jrkabao.dao.CityDao;
import cn.rongdao.jrkabao.dao.FundAndActivityCenterUrlDao;
import cn.rongdao.jrkabao.model.information.QuotaDataModel;
import cn.rongdao.jrkabao.model.main.MainModel;
import cn.rongdao.jrkabao.model.message.LoanMessageModel;
import cn.rongdao.jrkabao.ui.city.CityActivity;
import cn.rongdao.jrkabao.ui.city.event.UpdateCityNameEvent;
import cn.rongdao.jrkabao.ui.information.MyQuotaActivity;
import cn.rongdao.jrkabao.ui.information.event.QuotaChangeEvent;
import cn.rongdao.jrkabao.ui.loan.LoanCommitActivity;
import cn.rongdao.jrkabao.ui.loan.MultiPusuListActivity;
import cn.rongdao.jrkabao.ui.login.LoginActivity;
import cn.rongdao.jrkabao.ui.main.mainfragment.adapter.FragmentMainAdapter;
import cn.rongdao.jrkabao.ui.message.LoanMessageActivity;
import cn.rongdao.jrkabao.ui.webview.WebViewActivity;
import cn.rongdao.jrkabao.util.LoginUtil;
import cn.rongdao.jrkabao.util.NumberUtil;
import cn.rongdao.jrkabao.widget.CustomCircleView;

/**
 * Created by jack on 17/5/9
 * 贷款页
 */

public class FragmentLoan extends BaseViewPagerFragment implements FRBaseRecyclerAdapter.OnItemClickListener<FRBaseRecyclerViewHolder<ProductListBean>>, View.OnClickListener {


    private static final int TITLE_HEIGHT = 44;//title的背景高度
    private static final int HEADER_HEIGHT = 145;//header的背景高度
    private static final int SHORT_HEADER_HEIGHT = 64;//向上滑动的时候header的背景高度

    @BindView(R.id.fl_titlebar)
    TitleBarUIComponent mTitleBarUIComponent;
    @BindView(R.id.fl_fly_imageview)
    ImageView mFlyImageView;
    @BindView(R.id.fl_ptr_framelayout)
    PtrRecyclerViewUIComponent ptrRecyclerViewUIComponent;
    @BindView(R.id.fl_quota_progressView)
    CustomCircleView mCustomCircleView;
    @BindView(R.id.fl_tv_increase_amount)
    TextView mIncreaseAmount;
    @BindView(R.id.fl_activity_center)
    ImageView mActivityCenter;
    @BindView(R.id.fl_header_view)
    View mHeaderBgView;
    @BindView(R.id.fl_bar_layout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.fl_titlebar_copy)
    TitleBarUIComponent mTitleBarUIComponentCopy;
    @BindView(R.id.fl_titlebar_copy_ll)
    LinearLayout mTitleBarUIComponentCopyLl;

    private String mProductId;
    private String mOrgName;
    private List<ProductListBean> mProductListBeanList = new ArrayList<>();
    private FragmentMainAdapter mFragmentMainAdapter;
    private String mCateId;
    private ProductListBean mProductListBean;
    private int flyBannerJumptype = 2;
    private String flyBannerJumpUrl = "";
    private boolean isVisibleToUser = true;//默认是认为当前页面展示的状态
    private String mActivityCenterUrl;
    private LinearLayout mShortViewLL;
    private TextView mShortViewTvAmount;
    private TextView mShortViewTvClick;
    private int mHeaderShowStatus = 0;
    private int mHeaderHeightOffset;
    private View mFooterView;


    @Override
    protected int layoutRes() {
        return R.layout.fragment_loan;
    }

    @Override
    protected void onViewReallyCreated(View view) {
        super.onViewReallyCreated(view);
        EventBus.getDefault().register(this);
        //设置进度是否需要小圆
        mCustomCircleView.setNeedSmallCircle(false);
        mFragmentMainAdapter = new FragmentMainAdapter(getContext(), this);
        RecyclerAdapterWithHF mRecyclerAdapterWithHF = new RecyclerAdapterWithHF(mFragmentMainAdapter);
        ptrRecyclerViewUIComponent.setLayoutManager(new LinearLayoutManager(getContext()));
        ptrRecyclerViewUIComponent.setAdapter(mRecyclerAdapterWithHF);
        ptrRecyclerViewUIComponent.setBackground(R.color.layout_bg);
        ptrRecyclerViewUIComponent.setSmlieViewColor(R.color.colorPrimary);
        ptrRecyclerViewUIComponent.setHeaderType(PtrClassicDefaultHeader.HEADER_TYPE_ANIM);
        mFooterView = LayoutInflater.from(getContext()).inflate(R.layout.layout_home_footer, ptrRecyclerViewUIComponent, false);
        mRecyclerAdapterWithHF.addFooter(mFooterView);

        mShortViewLL = findView(R.id.fl_ll_short_view);
        mShortViewTvAmount = findView(R.id.fl_tv_short_view_amount);
        mShortViewTvClick = findView(R.id.fl_tv_short_view_click);
        initTitleBar(mTitleBarUIComponent);
        initTitleBar(mTitleBarUIComponentCopy);
        initListener();
        initCircleView();
    }


    /*初始化半圆的初始值*/
    private void initCircleView() {
        setQuotaDefaultData();
    }

    @Override
    protected void lazyLoad() {
        ptrRecyclerViewUIComponent.delayRefresh();
    }

    public void getData() {
        MainModel.getInstance().execute(new FRBaseObserver<MainBean>(this) {
            @Override
            protected void onBaseNext(final MainBean data) {
                if (null != data) {
                    parseData(data);
                    mFooterView.setVisibility(View.VISIBLE);
                }
                ptrRecyclerViewUIComponent.refreshComplete();
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                ptrRecyclerViewUIComponent.refreshComplete();
            }
        });
    }

    private void setFlyBannerData(MainBean.FlyBannerBean data) {
        boolean reapplyStatus = data != null && data.getState() == 1;
        if (reapplyStatus) {
            mFlyImageView.setVisibility(View.VISIBLE);
            flyBannerJumpUrl = data.getUrl();
            flyBannerJumptype = data.getJump_type();
            FRImageLoad.loadImage(data.getLogo(), mFlyImageView);
        } else {
            mFlyImageView.setVisibility(View.INVISIBLE);
        }
    }


    private void initTitleBar(TitleBarUIComponent titleBarUIComponent) {
        titleBarUIComponent.initRight(R.drawable.icon_no_message, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.isLogin(getContext())) {
                    LoanMessageActivity.start(getContext());
                }
            }
        });
        titleBarUIComponent.initTitle("贷款");
        titleBarUIComponent.initLeft(TextUtils.isEmpty(CityDao.getInstance().getCityName()) ? "杭州市" : CityDao.getInstance().getCityName(), R.drawable.icon_location, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityActivity.start(getContext());
            }
        });
    }


    private void initListener() {
        mHeaderHeightOffset = FRDisplayMetrics.dp2px(getContext(), HEADER_HEIGHT - SHORT_HEADER_HEIGHT);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    ptrRecyclerViewUIComponent.setCanRefresh(true);
                    mShortViewLL.setVisibility(View.INVISIBLE);
                } else {
                    ptrRecyclerViewUIComponent.setCanRefresh(false);
                    if (mHeaderShowStatus == 1) {
                        setShortHeaderAnim(verticalOffset);
                        if (mShortViewLL.getVisibility() == View.VISIBLE) {
                            return;
                        }
                        mShortViewLL.setVisibility(View.VISIBLE);
                        mTitleBarUIComponentCopyLl.setVisibility(View.INVISIBLE);
                    } else {
                        if (mTitleBarUIComponentCopyLl.getVisibility() == View.VISIBLE) {
                            return;
                        }
                        mShortViewLL.setVisibility(View.INVISIBLE);
                        mTitleBarUIComponentCopyLl.setVisibility(View.VISIBLE);
                    }
                }

            }
        });

        ptrRecyclerViewUIComponent.setOnPullToRefreshListener(new OnPullToRefreshListener() {
            @Override
            public void onPullToRefresh() {
                getQuoteData();
                getMessageInfo();
                if (ptrRecyclerViewUIComponent.isAutoRefresh()) {
                    return;
                }
                getData();
            }
        });


        mFlyImageView.setOnClickListener(this);
        mActivityCenter.setOnClickListener(this);
        mIncreaseAmount.setOnClickListener(this);
        mShortViewTvClick.setOnClickListener(this);
        mShortViewLL.setOnClickListener(this);

    }

    /**
     * 向上滑动的时候，头部的动画效果
     *
     * @param verticalOffset
     */
    void setShortHeaderAnim(int verticalOffset) {
        float slipPercent = (verticalOffset + mHeaderHeightOffset * 1.0f) / mHeaderHeightOffset;
        mShortViewLL.setAlpha(1 - slipPercent);
        if (slipPercent > 0) {
            mShortViewLL.scrollTo(0, (int) (slipPercent * FRDisplayMetrics.dp2px(getContext(), SHORT_HEADER_HEIGHT)));
        } else {
            mShortViewLL.scrollTo(0, 0);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_tv_short_view_click:
            case R.id.fl_tv_increase_amount:
                if (LoginUtil.isLogin(getContext())) {
                    MyQuotaActivity.start(getContext());
                }
                break;

            case R.id.fl_activity_center:
                if (LoginUtil.isLogin(getContext())) {
                    if (!TextUtils.isEmpty(mActivityCenterUrl)) {
                        WebViewActivity.start(getContext(), mActivityCenterUrl);
                    }
                }
                break;
            case R.id.fl_fly_imageview:
                if (flyBannerJumptype == 2)
                    MultiPusuListActivity.start(getContext(), "2,3,4", MultiPusuListActivity.CLASSIFY_REAPPLY, "快速拿钱");
                else
                    WebViewActivity.start(getContext(), flyBannerJumpUrl);
                break;
        }
    }

    private void getQuoteData() {

        QuotaDataModel.getInstance().execute(new FRBaseObserver<QuotaBean>(this) {
            @Override
            protected void onBaseNext(QuotaBean data) {

                mCustomCircleView.setCurrentAngle(data.getValidation_num() * 20);
                if (data.getQuota() == 0) {
                    mCustomCircleView.setCenterTextNumber(" " + getResources().getString(R.string.home_default_amount), 18);
                    setmShortViewTvAmountText(getResources().getString(R.string.home_default_amount));

                    mIncreaseAmount.setText(R.string.default_increase_the_amount);
                    mShortViewTvClick.setText(R.string.default_increase_the_amount);
                    return;
                }
                mCustomCircleView.setCenterTextNumber(NumberUtil.splitNum(data.getQuota()));
                setmShortViewTvAmountTextNumber(NumberUtil.splitNum(data.getQuota()));
                mIncreaseAmount.setText(R.string.increase_the_amount);
                mShortViewTvClick.setText(R.string.increase_the_amount);
            }

            @Override
            protected void onBaseError(Throwable t) {
                handingExceptions(t, false);
            }
        });
    }

    private void getMessageInfo() {
        LoanMessageModel.getInstance().execute(new FRBaseObserver<List<LoanMessageBean>>(this) {
            @Override
            protected void onBaseNext(List<LoanMessageBean> data) {
                setTitleHaveMessageOrNot(data.size() > 0, mTitleBarUIComponent);
                setTitleHaveMessageOrNot(data.size() > 0, mTitleBarUIComponentCopy);
            }
        });
    }

    public void setTitleHaveMessageOrNot(boolean haveMessageOrNot, TitleBarUIComponent titleBarUIComponent) {
        if (haveMessageOrNot) {
            titleBarUIComponent.setRightBtnRes(R.drawable.icon_have_message);
        } else {
            titleBarUIComponent.setRightBtnRes(R.drawable.icon_no_message);
        }
    }


    private void parseData(MainBean mainBean) {
        setHeaderShowStatus(mainBean.getXinsudai_myloanamount());
        setFlyBannerData(mainBean.getFly_banner());
        setActivityCenterData(mainBean.getActivity_index());
        saveUserCenterActivity(mainBean.getActivity_usercenter());
        String helpCenterUrl = mainBean.getHelpcenter_url();
        FundAndActivityCenterUrlDao.getInstance().updateBean(new FundAndActivityCenterUrlBean(helpCenterUrl, mainBean.getPublic_fund_url(), mainBean.getOther_loan_url()));
        mProductListBeanList.clear();
        mProductListBeanList.addAll(mainBean.getProduct_list());
        mFragmentMainAdapter.setDataList(mProductListBeanList, true);
    }

    private void setHeaderShowStatus(int status) {
        mHeaderShowStatus = status;
        if (mHeaderShowStatus == 1) {
            showHeader();
        } else {
            hideHeader();
        }
    }

    private void showHeader() {
        if (mCustomCircleView.getVisibility() == View.VISIBLE)
            return;
        FRDisplayMetrics.setWidgetScaleAnim(mHeaderBgView.getMeasuredHeight(), FRDisplayMetrics.dp2px(getContext(), HEADER_HEIGHT), mHeaderBgView);
        mTitleBarUIComponent.initTitle("");
        mCustomCircleView.setVisibility(View.VISIBLE);
        mIncreaseAmount.setVisibility(View.VISIBLE);
    }

    private void hideHeader() {
        if (mCustomCircleView.getVisibility() == View.GONE)
            return;
        FRDisplayMetrics.setWidgetScaleAnim(mHeaderBgView.getMeasuredHeight(), FRDisplayMetrics.dp2px(getContext(), TITLE_HEIGHT), mHeaderBgView);
        mCustomCircleView.setVisibility(View.GONE);
        mIncreaseAmount.setVisibility(View.GONE);
        mTitleBarUIComponent.initTitle("贷款");
        mTitleBarUIComponentCopy.initTitle("贷款");
    }

    private void saveUserCenterActivity(ActivityIndex activityUsercenter) {
        ActivityCenterDao.getInstance().updateObject(activityUsercenter);
    }


    private void setActivityCenterData(ActivityIndex activityIndex) {
        if (activityIndex == null)
            return;
        mActivityCenter.setVisibility(activityIndex.getState() == 1 ? View.VISIBLE : View.INVISIBLE);
        FRImageLoad.loadImage(activityIndex.getLogo(), mActivityCenter);
        mActivityCenterUrl = activityIndex.getUrl();
    }


    /**
     * 通过一系类的设定，在切换Activity的时候会调用onResume中的refreshDataWhenChangeFragmentOrActivity，在切换Fragment的时候会调用onHiddenChanged中的refreshDataWhenChangeFragmentOrActivity
     * 避免了重复调用
     *
     */
    void refreshDataWhenChangeFragmentOrActivity(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            getData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    protected void onFragmentHiddenChanged(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;
        refreshDataWhenChangeFragmentOrActivity(isVisibleToUser);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void updateCityName(UpdateCityNameEvent updateCityNameEvent) {
        mTitleBarUIComponent.setLeftTextContent(CityDao.getInstance().getCityName());
        mTitleBarUIComponentCopy.setLeftTextContent(CityDao.getInstance().getCityName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void updateCityName(QuotaChangeEvent updateCityNameEvent) {
        getQuoteData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void compulsoryDownLineMessage(CompulsoryDownLineEvent compulsoryDownLineEvent) {
        LoginUtil.logout(getActivity());
        setQuotaDefaultData();
        //表示用户在刚刚进入应用时就被挤退，重新加载数据
        if (mProductListBeanList.size() == 0) {
            getData();
        }
    }

    void setQuotaDefaultData() {
        mCustomCircleView.setCurrentAngle(0);
        mCustomCircleView.setCenterTextNumber(" " + getString(R.string.home_default_amount), 18);
        setmShortViewTvAmountText(getString(R.string.home_default_amount));
        mIncreaseAmount.setText(R.string.default_increase_the_amount);
        mShortViewTvClick.setText(R.string.default_increase_the_amount);
    }


    @Override
    public void onItemClick(FRBaseRecyclerViewHolder<ProductListBean> productListBeanFRBaseRecyclerViewHolder, int position) {
        mProductListBean = mProductListBeanList.get(position);
        mOrgName = mProductListBean.getOrg_name();
        mProductId = mProductListBean.getProduct_id();
        mCateId = mProductListBean.getCate_id();
        if (notYetLoggedIn()) return;
        startLoanProduct();

    }

    boolean notYetLoggedIn() {
        if (!LoginUtil.isLogin()) {
            startActivityForResult(new Intent(getContext(), LoginActivity.class), InfoConstant.REQUEST_CODE_LOANFRAGMENT_LOGINACTIVITY);
            return true;
        }
        return false;
    }

    private void startLoanProduct() {

        if (mProductListBean.getJump_type() == 1) {
            WebViewActivity.start(getContext(), mProductListBean.getOrg_link());
            return;
        }
        if (startMultiPustListActivity()) return;

        LoanCommitActivity.start(getContext(), mCateId, mProductId, mOrgName);
    }

    private boolean startMultiPustListActivity() {
        if ("1".equals(mProductListBean.getIs_apply()) && "1".equals(mProductListBean.getIs_push_all())) {
            MultiPusuListActivity.start(getContext(), mCateId, MultiPusuListActivity.CLASSIFY_MULTI_PUSH, mOrgName);
            return true;
        }
        return false;
    }

    private void setmShortViewTvAmountText(String tv) {
        mShortViewTvAmount.setTextSize(18);
        mShortViewTvAmount.setText(tv);
    }

    private void setmShortViewTvAmountTextNumber(String tv) {
        Spannable span = new SpannableString(TextUtils.concat(tv, "元"));
        span.setSpan(new AbsoluteSizeSpan(FRDisplayMetrics.dp2px(getContext(), 30)), 0, tv.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(FRDisplayMetrics.dp2px(getContext(), 15)), tv.length(), span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mShortViewTvAmount.setText(span);
    }

}